package com.threeti.mecool.core.application.acl;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.threeti.mecool.core.domain.model.acl.User;
import com.threeti.mecool.core.infrastructure.persistence.UserRepository;
import com.threeti.mecool.core.util.SecurityUtil;

@Service
public class UserServiceImpl implements UserService {
  @Autowired
  private UserRepository userRepository;

  @Override
  public UserAdapter loadUserByUsername(String loginName) throws UsernameNotFoundException, DataAccessException {
    final User user = userRepository.findByloginName(loginName);
    if (user == null)
      throw new UsernameNotFoundException("用户名不存在: " + loginName);
    return new UserAdapter(user);
  }

  @Override
  public User getUserFromSession() {
    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();
    Object principal = authentication.getPrincipal();
    if (principal instanceof UserAdapter) {
      UserAdapter userDetails = (UserAdapter) principal;
      return userDetails.getUser();
    }
    return null;
  }

  @Override
  @Transactional
  public User register(String loginName, String name, String password) {
    if (StringUtils.isBlank(loginName))
      throw new RuntimeException("帐号为空");
    if (StringUtils.isBlank(password))
      throw new RuntimeException("密码为空");
    
    User found = userRepository.findByloginName(loginName);
    if (found != null)
      throw new RuntimeException("帐号已存在: " + loginName);

    User user = userRepository.saveAndFlush((new User(loginName, name, password)));
    SecurityUtil.putUserInSession(new UserAdapter(user));
    return user;
  }

}
